<template>
  <div class="main_box">
    <h1>AED急救辅助</h1>

    <el-collapse v-model="collapseActive">
      <el-collapse-item name="5" title="管理范围">
        <el-row :gutter="20" class="row" v-if="operationalScope.length > 0">
          <el-col :span="4" v-for="(item, index) in operationalScope" :key="index">
            <div :class="item.name === operationalScopeName ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(1, item.name)">{{ item.name }}</div>
          </el-col>
          <el-col :span="24" v-if="scopeAddress.length > 0" style="display: flex; align-items: center;">
            <h3 style="margin-right: 20px">选择区域:</h3>
            <el-cascader style="width: 300px" :props="{ checkStrictly: true }" placeholder="请选择区域" filterable :clearable="true" :options="scopeAddress" @change="handRegionalChoices" />
          </el-col>
        </el-row>
        <div class="empty" v-if="operationalScope.length === 0">
          该账号没有管理范围，请联系管理员设置
        </div>
      </el-collapse-item>

      <el-collapse-item name="6" title="社区" v-if="communitySet.length > 0">
        <el-row :gutter="20" class="row">
          <el-col :span="4" v-for="item in communitySet" :key="item.id">
            <div :class="communityId === item.id ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(2, item.id)">{{ item.name }}</div>
          </el-col>
        </el-row>
      </el-collapse-item>

      <template v-if="!skeletonShow">
        <el-collapse-item name="1" title="小区" v-if="districts.length > 0">
          <template slot="title">
            <div class="title">
              <span>小区</span>
              <div class="search" @click='stopProp'>
                <el-input placeholder="请输入小区名称" v-model="searchDistrictName" clearable class="input-with-select" size="small" @input="handleNeighborhoodSearch" />
              </div>
            </div>
          </template>

          <el-row :gutter="20" class="row">
            <el-col :span="4" v-for="item in districts" :key="item.id">
              <div :class="cid === item.id ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(3, item.id)">{{ item.name }}</div>
            </el-col>
          </el-row>
        </el-collapse-item>
        <div class="empty" v-else="false">
          未查找小区数据，请联系管理员配置
        </div>
        <template v-if="buildingStructure && buildingStructure.length && districts.length > 0">
          <el-collapse-item name="2" title="楼栋" v-if="buildingStructure.length > 0">
            <el-row :gutter="20" class="row">
              <el-col :span="4" v-for="item in buildingStructure" :key="item.id">
                <div :class="buildingIds.bldId === item.id ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(4, item.id)">{{ item.name }}</div>
              </el-col>
            </el-row>
          </el-collapse-item>

          <el-collapse-item name="3" title="单元" v-if="unitList.length > 0">
            <el-row :gutter="20" class="row">
              <el-col :span="4" v-for="item in unitList" :key="item.id">
                <div :class="buildingIds.unitId === item.id ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(5, item.id)">{{ item.name }}</div>
              </el-col>
            </el-row>
          </el-collapse-item>

          <el-collapse-item name="4" title="楼层" v-if="floorList.length > 0">
            <el-row :gutter="20" class="row">
              <el-col :span="4" v-for="item in floorList" :key="item.id">
                <div :class="buildingIds.floorId === item.id ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(6, item.id)">{{ item.name }}</div>
              </el-col>
            </el-row>
          </el-collapse-item>

          <el-collapse-item name="5" title="门牌" v-if="houseNumberList.length > 0">
            <el-row :gutter="20" class="row">
              <el-col :span="4" v-for="(item, index) in houseNumberList" :key="index">
                <div :class="buildingIds.houseNumberId === item.id ? 'box-card box-card-active' : 'box-card'" @click="handleChangesInRegion(7, {id: item.id, name: item.name})">{{ item.name }}</div>
              </el-col>
            </el-row>
          </el-collapse-item>
        </template>
        <div class="empty" v-if="(!buildingStructure  ||  buildingStructure.length === 0) && districts.length > 0">
          该小区下没有楼栋数据
        </div>
      </template>
      <template v-else>
        <div class="skeleton">
          <SkeletonLoader :itemCount="7" />
        </div>
      </template>

    </el-collapse>
    <div class="footer" v-if="buildingIds.houseNumberId">
      <el-button type="danger" style="width: 300px" @click="handleSendSosAlert" v-loading.fullscreen.lock="loading">AED报警</el-button>
    </div>
  </div>
</template>

<script>
import VillageApplyApi from "@/api/address/villageApply";
import to from "@/utils/to";
import VillageAreaApi from "@/api/address/villageArea";
import OrderApi from "@/api/order/order";
import regionData from "@/components/regionData.json"
import {TreeValueGetter} from "@/utils";
import AuthApi from "@/api/system/auth";
import CommunityApi from "@/api/address/community";
import SkeletonLoader from "@/components/SkeletonLoader.vue";

export default {
  name: "AedFirstAid",
  components: {SkeletonLoader},
  data() {
    return {
      collapseActive: ['1','2','3','4','5','6','7'],
      operationalScope: [],
      operationalScopeName: '',
      loading: false,
      skeletonShow: false,
      scopeAddress: [], //  地区数据
      searchDistrictName: '',
      communitySet: [], // 社区列表
      districts: [], // 小区列表
      cid: 0, // 小区ID
      communityId: 0, // 社区id
      buildingStructure: undefined, // 楼栋层树
      buildingIds: {  // 楼栋层id
        bldId: 0,
        unitId: 0,
        floorId: 0,
        houseNumberId: 0
      },
      houseNumberName: '',  // 门牌号名称
    }
  },
  mounted() {
    // 拿到账号管理范围
    const userInfo = sessionStorage.getItem("user_info") ? JSON.parse(sessionStorage.getItem("user_info")) : undefined;
    if (userInfo && userInfo.relationRoleId) {
      const { relationRoleId } = userInfo;
      AuthApi.listVillage({adminId: relationRoleId}).then(res => {
        this.operationalScope = this.handleManageScopeData(res.data)
        this.operationalScopeName = this.operationalScope[0].name
      })
    }
  },
  computed: {
    /**
     * 获取单元
     * @returns {*|*[]}
     */
    unitList() {
      const { bldId } = this.buildingIds
      const unit = this.buildingStructure.find(c => c.id === bldId)
      if (unit && unit.children) {
        this.buildingIds.unitId = unit.children[0].id
        return unit.children
      } else {
        return []
      }
    },
    /**
     * 获取层
     * @returns {*|*[]}
     */
    floorList() {
      const { unitId } = this.buildingIds
      const floor = this.unitList.find(c => c.id === unitId)
      if (floor && floor.children) {
        this.$set(this.buildingIds, "floorId", floor.children[0].id)
        return floor.children
      } else {
        return []
      }
    },
    /**
     * 获取门牌
     * @returns {*|*[]}
     */
    houseNumberList() {
      const { floorId } = this.buildingIds
      const floor = this.floorList.find(c => c.id === floorId)
      if (floor && floor.children) {
	      console.log(floor.children)
        return floor.children
      } else {
        return []
      }
    },
  },
  watch: {
    cid(newVal, oldVal) {
      this.handleFetchFloorLevelData(newVal)
    },
    communityId(newVal) {
      if (newVal) this.handleGetNearbyList({communityId: newVal})
    },
    operationalScopeName(newVal) {
      this.communitySet = []
      this.communityId = 0
      this.districts = [];
      this.cid = 0;

      const projectScope = this.operationalScope.filter(c => c.name === newVal)[0]
      // 只有省市级别才显示街道区域选择
      if (projectScope.levels <= 2) {
        if (projectScope.name === '全国') {
          this.scopeAddress = regionData.data
        } else {
          this.scopeAddress = TreeValueGetter(regionData.data, projectScope.regionId, 'value').children || []
        }
      } else {
        this.scopeAddress = []
        // 如果是小区 直接组成小区数据 如果是区直接搜索小区 如果是社区搜索小区
        if (projectScope.levels === 6) {
          this.districts = [{id: projectScope.villageId, name: projectScope.villageName}]
          this.cid = projectScope.villageId
        } else if (projectScope.levels === 5) {
          const {provinceId, cityId, areaId, communityId} = projectScope
          this.handleGetNearbyList({provinceId, cityId, areaId, communityId})
        } else if (projectScope.levels === 3) {
          const {provinceId, cityId, areaId} = projectScope
          this.handleGetNearbyList({provinceId, cityId, areaId})
        }
      }

      // 经营范围是街道 => 搜索社区
      if (projectScope.levels === 4) {
        this.handleGetCommunityList({ streetId: projectScope.streetId })
      }
    }
  },
  methods: {

    /**
     * 获取社区列表
     * @param params
     */
    handleGetCommunityList(params) {
      CommunityApi.listIdName(params).then(res => {
        this.communityId = res.data[0].id
        this.communitySet = res.data
      })
    },

    /**
     * 区域选择器change 获取小区
     * @param val
     */
    handRegionalChoices(val) {
      const addressId = val[val.length - 1]
      const params = {}
      if (addressId.toString().length === 2) params.provinceId = addressId
      if (addressId.toString().length === 4) params.cityId = addressId
      if (addressId.toString().length === 6) params.areaId = addressId
      if (addressId.toString().length === 9) params.streetId = addressId
      this.handleGetNearbyList(params)
    },

    /**
     * 获取小区列表
     * @returns {Promise<void>}
     */
    handleGetNearbyList(params) {
      this.skeletonShow = true
      VillageApplyApi.villageList(params).then(res => {
        this.districts = res.data
        this.cid = res.data.length > 0 ? res.data[0].id : 0
        setTimeout(() => {
          this.skeletonShow = false
        }, 200)
      }).catch(() => {
        this.skeletonShow = false
      })
    },

    /**
     * 获取楼栋层数据
     * @param cid
     */
    handleFetchFloorLevelData(cid) {
      if (!cid) {
        this.buildingIds = this.$options.data().buildingIds
        this.buildingStructure = []
      } else {
        VillageAreaApi.getListTree({villageId: cid}).then(res => {
          this.buildingStructure = res.data
          if (res.data && res.data.length > 0) {
            const { buildingStructure } = this
            this.buildingIds = {
              bldId: buildingStructure[0].id,
              unitId: buildingStructure[0].id,
            }
          }
        })
      }
    },

    /**
     * 阻止冒泡
     * @param e
     */
    stopProp(e) {
      e.stopPropagation()
    },

    /**
     * 搜索小区名称 模糊查询
     */
    handleNeighborhoodSearch() {
      const query = this.searchDistrictName.toLowerCase();
       if (this.searchDistrictName) {
         this.districts = this.districts.filter(item => item.name.toLowerCase().includes(query))
         this.cid =  this.districts.length > 0 ?  this.districts[0].id : 0
       } else {
         this.handleGetNearbyList()
       }

    },

    /**
     * 发送sos警报
     */
    handleSendSosAlert() {
      this.$confirm(`确定要为门牌号为  ${this.houseNumberName} 发送AED急救报警吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const { houseNumberId } = this.buildingIds
        OrderApi.AlarmAddressOrder({alarmType: 'sos', houseNumberId}).then(res => {
          this.loading = false
          this.$notify({
            title: '成功',
            message: '发送报警成功',
            type: 'success'
          });
        }).catch(() => {
          this.loading = false
        })
      })
    },

    /**
     * 处理管理范围数据
     * @param operationalScope
     */
    handleManageScopeData(operationalScope) {
      operationalScope.forEach((item, index) => {
        switch (item.levels) {
          case 1:
            operationalScope[index].name = item.provinceName
            operationalScope[index].regionId = item.provinceId
            break;
          case 2:
            operationalScope[index].name = item.provinceName === item.cityName ? item.provinceName : `${item.provinceName}-${item.cityName}`
            operationalScope[index].regionId = item.cityId
            break;
          case 3:
            operationalScope[index].name = `${item.provinceName}-${item.cityName}-${item.areaName}`
            operationalScope[index].regionId = item.areaId
            break;
          case 4:
            operationalScope[index].name = `${item.provinceName}-${item.cityName}-${item.areaName}-${item.streetName}`
            operationalScope[index].regionId = item.streetId
            break
          case 5:
            operationalScope[index].name = `${item.provinceName}-${item.cityName}-${item.areaName}-${item.communityName}`
            break;
          case 6:
            operationalScope[index].name = `${item.provinceName}-${item.cityName}-${item.areaName}-${item.villageName}`
            break;
        }
      })
      return operationalScope
    },

    /**
     * 任何一级地区楼栋层切换都要清除门牌号
     * @param level
     * @param value
     */
    handleChangesInRegion(level, value) {
      switch (level) {
        case 1:
          this.operationalScopeName = value
	        this.$set(this.buildingIds, "houseNumberId", 0)
          break;
        case 2:
          this.communityId = value
	        this.$set(this.buildingIds, "houseNumberId", 0)
          break;
        case 3:
          this.cid = value
	        this.$set(this.buildingIds, "houseNumberId", 0)
          break;
        case 4:
          this.$set(this.buildingIds, "bldId", value)
	        this.$set(this.buildingIds, "houseNumberId", 0)
          break;
        case 5:
          this.$set(this.buildingIds, "unitId", value)
	        this.$set(this.buildingIds, "houseNumberId", 0)
          break;
        case 6:
          this.$set(this.buildingIds, "floorId", value)
	        this.$set(this.buildingIds, "houseNumberId", 0)
          break;
	      case 7:
		      this.$set(this.buildingIds, "houseNumberId", value.id);
		      this.$set(this.buildingIds, "houseNumberName", value.name);
					break;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/views/content.scss";

h1 {
  font-size: 40px;
  text-align: center;
  margin: 20px 0;
}
.main_box {
  padding: 0 30px;
  padding-bottom: 100px;
  .row {
    width: 100%;
    ::v-deep .el-col {
      margin-bottom: 10px
    }
  }
  .title {
    width: 100%;
    display: flex;
    justify-content: space-between;
    position: relative;
  }
  .search {
    position: absolute;
    right: 40px;
    width: 300px;
  }

  .box-card {
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40px;
    color: #333333;
    padding: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  }
  .box-card-active {
    background: #49b07a;
    color: white;
  }
  .box-card:hover {
    cursor: pointer;
  }
  ::v-deep .el-collapse-item__header {
    font-size: 20px;
    text-align: center;
    display: flex;
    justify-content: space-between;
  }
  ::v-deep .el-collapse-item__content {
    padding: 20px;
  }

  .footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    padding-left: 40px;
    box-sizing: border-box;
  }

  .empty {
    width: 100%;
    margin: 40px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    font-weight: bold;
  }

  .skeleton {
    width: 100%;
    height: 500px;
  }
}
</style>
